package com.sqx.modules.app.service.impl;

import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sqx.common.utils.Result;
import com.sqx.modules.app.dao.UserMoneyDetailsDao;
import com.sqx.modules.app.dao.UserVipDao;
import com.sqx.modules.app.entity.UserEntity;
import com.sqx.modules.app.entity.UserMoneyDetails;
import com.sqx.modules.app.entity.UserVip;
import com.sqx.modules.app.response.ChangeRecordResponse;
import com.sqx.modules.app.service.UserMoneyDetailsService;
import com.sqx.modules.orders.dao.OrdersDao;
import com.sqx.modules.orders.entity.Orders;
import com.sqx.modules.pay.dao.CashOutDao;
import com.sqx.modules.pay.entity.CashOut;
import com.sqx.modules.pay.service.CashOutService;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class UserMoneyDetailsServiceImpl extends ServiceImpl<UserMoneyDetailsDao, UserMoneyDetails> implements UserMoneyDetailsService {
    @Autowired
    private OrdersDao ordersDao;
    @Autowired
    private CashOutDao cashOutDao;
    @Autowired
    private UserVipDao userVipDao;
    @Override
    public Result queryUserMoneyDetails(Integer page, Integer limit, Long userId,Integer classify,Integer type) {
        IPage<UserMoneyDetails> page1 = new Page(page, limit);
        QueryWrapper<UserMoneyDetails> queryWrapper = new QueryWrapper();
        queryWrapper.eq("user_id", userId);
        if(classify!=null){
            queryWrapper.eq("classify", classify);
        }
        if(type!=null){
            queryWrapper.eq("type", type);
        }
        queryWrapper.orderByDesc("create_time");
        return Result.success().put("data", baseMapper.selectPage(page1, queryWrapper));
    }

    @Override
    public Double monthIncome(String date, Long userId) {
        return baseMapper.monthIncome(date,userId);
    }

    //vip充值交易明细
    @Override
    public Result changeRecord(Integer page, Integer limit, Long userId) {
        //会员类型0月/1季度/2年
        Page<Orders> userMoneyDetailsPage = new Page<>(ObjectUtils.isEmpty(page)?1:page, ObjectUtils.isEmpty(limit)?5:limit);
        LambdaQueryWrapper<Orders> userMoneyDetailsLambdaQueryWrapper = new LambdaQueryWrapper<>();
        userMoneyDetailsLambdaQueryWrapper.eq(Orders::getUserId,userId);
        userMoneyDetailsLambdaQueryWrapper.eq(Orders::getOrdersType,2);
        userMoneyDetailsLambdaQueryWrapper.in(Orders::getStatus,1,2);
        IPage<Orders> userMoneyDetailsIPage = ordersDao.selectPage(userMoneyDetailsPage, userMoneyDetailsLambdaQueryWrapper);
        for (Orders record : userMoneyDetailsIPage.getRecords()) {//vip的记录，是更新时间
            String createTime = record.getCreateTime();
            // 将字符串转换为LocalDateTime对象
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
            LocalDateTime dateTime = LocalDateTime.parse(createTime, formatter);
            String newDateString = null;
            if(record.getExpired()!=null){//过期时间不为空，表示是续费，过期时间就作为续费开始时间
                Date expired = record.getExpired();
                String expiredTime = DateUtil.format(expired, "yyyy-MM-dd HH:mm:ss");
                record.setCreateTime(expiredTime);
                LocalDateTime dateTime1 = LocalDateTime.parse(expiredTime, formatter);
                if (record.getVipNameType()==0){
                    dateTime1=dateTime1.plusMonths(1);
                } else if (record.getVipNameType()==1) {
                    dateTime1=dateTime1.plusMonths(3);
                } else if (record.getVipNameType()==2) {
                    dateTime1=dateTime1.plusYears(1);
                }
                record.setEndTime(dateTime1.format(formatter));
            }else {
                if (record.getVipNameType()==0){
                    LocalDateTime newDateTime = dateTime.plusMonths(1);
                    newDateString = newDateTime.format(formatter);
                } else if (record.getVipNameType()==1) {
                    LocalDateTime newDateTime = dateTime.plusMonths(3);
                    newDateString = newDateTime.format(formatter);
                } else if (record.getVipNameType()==2) {
                    LocalDateTime newDateTime = dateTime.plusYears(1);
                    newDateString = newDateTime.format(formatter);
                }
                record.setEndTime(newDateString);
            }

        }
        return Result.success().put("data",userMoneyDetailsIPage);
    }

    /**
     * 查询提现记录
     * @param page 页数
     * @param limit 条数
     * @param userId 用户di
     * @return 返回提现记录
     */
    @Override
    public Result withdrawRecord(Integer page, Integer limit, Long userId) {
        Page<UserMoneyDetails> userMoneyDetailsPage = new Page<>(ObjectUtils.isEmpty(page)?1:page, ObjectUtils.isEmpty(limit)?5:limit);
        LambdaQueryWrapper<UserMoneyDetails> userMoneyDetailsLambdaQueryWrapper = new LambdaQueryWrapper<>();
        userMoneyDetailsLambdaQueryWrapper.eq(UserMoneyDetails::getUserId,userId);
        userMoneyDetailsLambdaQueryWrapper.eq(UserMoneyDetails::getClassify,4);
        userMoneyDetailsLambdaQueryWrapper.eq(UserMoneyDetails::getType,2);
        IPage<UserMoneyDetails> userMoneyDetailsIPage = baseMapper.selectPage(userMoneyDetailsPage, userMoneyDetailsLambdaQueryWrapper);
        userMoneyDetailsIPage.getRecords().stream().map(o -> {
            String[] split = o.getTitle().split("：");
            o.setTitle(split[1]);//取出订单编号
            String[] split1 = o.getContent().split(",");
            o.setContent(split1[1]);//取出提现到哪里
            return o;
        }).collect(Collectors.toList());
        return Result.success().put("data",userMoneyDetailsIPage);
    }

    @Override
    public Result selCach(Integer page, Integer limit, Long userId) {
        LambdaQueryWrapper<CashOut> cashOutLambdaQueryWrapper = new LambdaQueryWrapper<>();
        cashOutLambdaQueryWrapper.eq(CashOut::getState,1);
        cashOutLambdaQueryWrapper.eq(CashOut::getUserId,userId);
        Page<CashOut> cashOutPage = new Page<>(page, limit);
        IPage<CashOut> cashOuts = cashOutDao.selectPage(cashOutPage,cashOutLambdaQueryWrapper);
        return Result.success().put("data",cashOuts);
    }
}
